#!/usr/bin/python3
# coding=utf-8

import pymysql
import sys

sys.path.append("./")
sys.path.append("../")
sys.dont_write_bytecode = True
from utils.config_helper import Global_Params
from utils.logger_helper import logObj


class MySQLHelper(object):
    def __init__(self, database):
        self.charset = "utf8"
        self.conn = None
        self.__set_mysql_info__(database)

    def __set_mysql_info__(self, database):
        if database:
            keys = database.keys()
            self.host = database["HOST"] if "HOST" in keys else None
            self.port = database["PORT"] if "PORT" in keys else 3306
            self.user = database["USER"] if "USER" in keys else None
            self.pwd = database["PWD"] if "PWD" in keys else None
            self.schema = database["SCHEMA"] if "SCHEMA" in keys else None
        else:
            logObj.error("数据库信息不完整{}".format(database))

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.pwd,
            database=self.schema,
        )
        self.cursor = self.conn.cursor()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

    def get_rawdata(self, sql):
        recordset = None
        cols = None
        try:
            self.connect()
            self.cursor.execute(sql)
            cols = self.cursor.description
            recordset = self.cursor.fetchall()

        except Exception as e:
            logObj.error("异常信息%{}".format(e))

        finally:
            self.close()

        return recordset, cols

    def insert(self, sql):
        return self.__edit(sql)

    def update(self, sql):
        return self.__edit(sql)

    def delete(self, sql):
        return self.__edit(sql)

    def __edit(self, sql):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql)
            self.conn.commit()
            self.close()
            logObj.debug("sql:{}; affect count:{}.".format(sql, count))
        except Exception as e:
            logObj.error("异常信息:%{}".format(e))
        return count


if __name__ == "__main__":
    db_info = {
        "HOST": "phoenix-t.xforceplus.com",
        "PORT": 22009,
        "USER": "root",
        "PWD": "testing",
        "SCHEMA": "xfb-data",
    }

    demo = MySQLHelper(db_info)
    print(demo.host)
    demo.connect()
